import { reactive, ref, toRefs, watch, inject } from "vue";

export default function () {
    let dataParams = reactive({
        arr_data: [],
        loading: true,
        search_btn: false,
        resultObj: null,
    });
    const $message = inject("$message");
    const totalNums = ref(0);
    const page = ref(1);
    const pageSize = ref(10); // 每页显示几条
    const pageSizeNum = ref([10, 20, 30, 40, 50]); //调整每页显示条数
    const search_text = ref("");

    // 正常分页
    function pubParams(getList) {
        dataParams.loading = true;
        dataParams.arr_data = [];
        getList();
    }

    // 刷新使用
    function pubRefreshParams(getList) {
        totalNums.value = 0;
        dataParams.loading = true;
        dataParams.arr_data = [];
        if (page.value === 1) {
            getList();
        } else {
            page.value = 1;
        }
    }

    // 列表
    async function getdata(promiseRes) {
        try {
            const res = await promiseRes;
            dataParams.loading = false;
            dataParams.search_btn = false;
            good_succ(res);
        } catch {
            dataParams.loading = false;
        }
    }

    function good_succ(res) {
        switch (res.data.code) {
            case 200:
                dataParams.resultObj = res.data;
                if (Array.isArray(res.data.data)) {
                    // 不分页
                    dataParams.arr_data = dataParams.resultObj.data;
                } else {
                    // 分页
                    let { current, records, total } = dataParams.resultObj.data;
                    total = Number(total);
                    // 最大页数限制在100
                    if (total >= 100 * pageSize.value) {
                        total = 100 * pageSize.value;
                    }
                    totalNums.value = total;
                    dataParams.arr_data = dataParams.arr_data.concat(records);
                }
                break;
            default:
                $message({ message: res.data.msg, type: "error" });
                break;
        }
    }

    function openPaging(getList) {
        // 切换每页显示条数
        watch(pageSize, (val) => {
            if (page.value === 1) {
                pubParams(getList);
            } else {
                page.value = 1;
            }
        });

        // 跳转第几页
        watch(page, (val) => {
            pubParams(getList);
        });
    }

    return {
        ...toRefs(dataParams),
        page,
        pageSize,
        pageSizeNum,
        totalNums,
        search_text,
        pubParams,
        pubRefreshParams,
        getdata,
        openPaging,
    };
}
